﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Northwind.NET.EDM.FE.WinForms.Controls;

namespace Northwind.NET.EDM.Reports
{
    public partial class ReportViewingUserControl : BaseUserControl
    {
        public ReportViewingUserControl()
        {
            InitializeComponent();
        }

        public override string FormCaption { get { return Settings.Resources.ReportViewingFormCaption; } }

        public enum ReportType
        {
            Catalog,
            ProductByCategory,
            AlphabeticalListOfProducts,
            CustomersLabelsReport,
            Shippers,
            Invoice,
            SummaryOfSalesByYear,
            SummaryOfSalesByQuarter,
            SalesByCategory,
            SalesTotalsByAmount,
            SalesByYear,
            SalesAnalysis,
            EmployeeSalesByCountry
        }

  
        public class MyReportsViewer
        {
 
            public EventHandler<EventArgs> LoadLookUpData;  

            private Microsoft.Reporting.WinForms.ReportViewer _v;
            public MyReportsViewer(Microsoft.Reporting.WinForms.ReportViewer v)
            {
                _v = v;
            }

            private ReportType _currentReportType;
            public ReportType CurrentReportType
            {
              get { return _currentReportType; }
            }

            public void LoadReport(
                   ReportType reportType,
                   string reportFileName,
                   string reportDataSetName,
                   object reportDataSet)
            {
                LoadReport(reportType, reportFileName, reportDataSetName, reportDataSet, null);    
            }
            public void LoadReport(
                   ReportType reportType,
                   string reportFileName,
                   string reportDataSetName,
                   object reportDataSet,
                   Microsoft.Reporting.WinForms.ReportParameter param1)
            {
                LoadReport(reportType, reportFileName, reportDataSetName, reportDataSet, param1, null);
            }

            public void LoadReport(
                   ReportType reportType,
                   string reportFileName, 
                   string reportDataSetName, 
                   object reportDataSet,
                   Microsoft.Reporting.WinForms.ReportParameter param1,
                   Microsoft.Reporting.WinForms.ReportParameter param2)
            {
                _v.Reset(); 

                if (LoadLookUpData != null) LoadLookUpData(this, new EventArgs());

                _currentReportType = reportType;

                string p = Northwind.NET.Utilities.Context.ExecutingAssemblyFolderName + @"Reports\" + reportFileName;
                System.IO.TextReader txt = new System.IO.StreamReader(p);

                _v.LocalReport.LoadReportDefinition(txt);
                txt.Close();

                _v.LocalReport.DataSources.Clear();

                Microsoft.Reporting.WinForms.ReportDataSource d = new Microsoft.Reporting.WinForms.ReportDataSource(
                    reportDataSetName,
                    reportDataSet
                    );
                _v.LocalReport.DataSources.Add(d);

                if (param1 != null) _v.LocalReport.SetParameters(param1);
                if (param2 != null) _v.LocalReport.SetParameters(param2);

                System.Threading.Thread.Sleep(100);

                _v.RefreshReport();
            }

            public void ViewAlphabeticalListOfProductsReport()
            {
                LoadReport(ReportType.AlphabeticalListOfProducts,  "AlphabeticalListOfProductsReport.rdlc", "SimpleReportsDataSet_AlphabeticalListOfProductsReport", Northwind.NET.BLL.Reports.AlphabeticalListOfProducts()); 
            }

            public void ViewCatalogReport()
            {
                LoadReport(ReportType.Catalog, "Catalog.rdlc", "SimpleReportsDataSet_CatalogReport", Northwind.NET.BLL.Reports.Catalog());
            }

            public void ViewShippersReport()
            {
                LoadReport(ReportType.Shippers, "ShippersReport.rdlc", "DataModelDataSet_Shipper", Northwind.NET.BLL.Reports.Shippers());
            }

            public void ViewProductByCategoryReport()
            {
                LoadReport(ReportType.ProductByCategory, "ProductByCategoryReport.rdlc", "SimpleReportsDataSet_ProductsByCategoryReport", Northwind.NET.BLL.Reports.ProductByCategory());
            }

            public void ViewCustomerLabelsReport(string countryName)
            {
                if (countryName == "(NONE)") countryName = null;
                dynamic reportDataSet = Northwind.NET.BLL.Reports.CustomerLabels(countryName);
                LoadReport(ReportType.CustomersLabelsReport, "CustomersLabelsReport.rdlc", "SimpleReportsDataSet_CustomerLabelsReport", reportDataSet);
            }

            public void ViewInvoiceReport(int? orderId)
            {
                LoadReport(ReportType.Invoice, "Invoice.rdlc", "SimpleReportsDataSet_InvoiceReportDataTable", Northwind.NET.BLL.Reports.Invoice(orderId));
            }

            public void ViewSummaryOfSalesByYearReport()
            {
                LoadReport(ReportType.SummaryOfSalesByYear, "SummaryOfSalesByYearReport.rdlc", "SimpleReportsDataSet_SummaryOfSalesByYearReport", Northwind.NET.BLL.Reports.SummaryOfSalesByYear());
            }

            public void ViewSummaryOfSalesByQuarterReport()
            {
                LoadReport(ReportType.SummaryOfSalesByYear, "SummaryOfSalesByQuarterReport.rdlc", "SimpleReportsDataSet_SummaryOfSalesByQuarterReport", Northwind.NET.BLL.Reports.SummaryOfSalesByQuarter());
            }

            public void ViewSalesByCategoryReport(int? categoryId)
            {
                LoadReport(ReportType.SalesByCategory, "SalesByCategoryReport.rdlc", "SimpleReportsDataSet_SalesByCategory", Northwind.NET.BLL.Reports.SalesByCategory(categoryId));
            }

            public void ViewSalesTotalsByAmountReport(int? yearNum)
            {
                LoadReport(ReportType.SalesTotalsByAmount, "SalesTotalsByAmountReport.rdlc", "SimpleReportsDataSet_SalesTotalsByAmountReport", Northwind.NET.BLL.Reports.SalesTotalsByAmountReport(yearNum));
            }
            public void ViewSalesByYearReport(int? yearNum)
            {
                //Parameters!yearNum.
                string paramValue = "1997";
                if (yearNum != null) paramValue = yearNum.ToString(); 
                else yearNum = 1997;
                Microsoft.Reporting.WinForms.ReportParameter param = new Microsoft.Reporting.WinForms.ReportParameter("yearNum", paramValue); 

                LoadReport(ReportType.SalesByYear, "SalesByYearReport.rdlc", "SimpleReportsDataSet_SalesByYear",
                           Northwind.NET.BLL.Reports.SalesByYearReport(yearNum), param);
            }

            public void ViewEmployeeSalesByCountryReport(DateTime? dateForm, DateTime? dateTo)
            {
                //Parameters!DateFrom.Value &amp; " to " &amp; Parameters!DateTo.Value
                Microsoft.Reporting.WinForms.ReportParameter param1 = null;
                Microsoft.Reporting.WinForms.ReportParameter param2 = null;
                if (dateForm == null || dateTo == null)
                {
                    param1 = new Microsoft.Reporting.WinForms.ReportParameter("DateFrom", "1/1/1997");
                    param2 = new Microsoft.Reporting.WinForms.ReportParameter("DateTo", "12/1/1997");
                }
                else
                {
                    param1 = new Microsoft.Reporting.WinForms.ReportParameter("DateFrom",
                                       string.Format("{0}/{1}/{2}", ((DateTime)dateForm).Month, ((DateTime)dateForm).Day, ((DateTime)dateForm).Year));
                    param2 = new Microsoft.Reporting.WinForms.ReportParameter("DateTo",
                                       string.Format("{0}/{1}/{2}", ((DateTime)dateTo).Month, ((DateTime)dateTo).Day, ((DateTime)dateTo).Year));
                }

                LoadReport(ReportType.EmployeeSalesByCountry, "EmployeeSalesByCountryReport.rdlc", "SimpleReportsDataSet_EmployeeSalesByCountryReport",
                    Northwind.NET.BLL.Reports.EmployeeSalesByCountryReport(dateForm, dateTo), param1, param2);
            }

            public void ViewSalesAnalysisReport()
            {
                LoadReport(ReportType.SalesAnalysis, "SalesAnalysisReport.rdlc", "SimpleReportsDataSet_SalesAnalysisReport", Northwind.NET.BLL.Reports.SalesAnalysisReport());
            }

        }


        private void refreshButton_Click(object sender, EventArgs e)
        {
            if (!_lookupDataLoaded) loadLookUpData(sender, e);

            //OrderIDTextBox - invoice
            //countryComboBox - CustomersLabelsReport
            //categoryIdComboBox - SalesByCategory
            //txtYear = SalesTotalsByAmount
            //txtYear = SalesByYear
            //dtpDateFrom, dtpDateTo - EmployeeSalesByCountryReport
            viewReport(_rpt.CurrentReportType);  
        }

        private void viewReport(ReportType reportType)
        {
            if (reportType == 0) reportType = ReportType.Catalog;

            int id = -1;
            bool test = false;

            switch (reportType)
            {
                case  ReportType.AlphabeticalListOfProducts:
                    _rpt.ViewAlphabeticalListOfProductsReport();
                    break;
                case ReportType.Catalog :
                    _rpt.ViewCatalogReport();
                    break;
                case ReportType.CustomersLabelsReport:
                    string countryName = null;
                    if (!string.IsNullOrEmpty(countryComboBox.Text)) countryName = countryComboBox.Text;   
                    _rpt.ViewCustomerLabelsReport(countryName);
                    break;
                case ReportType.EmployeeSalesByCountry:
                    {
                        DateTime? dateFrom = null;
                        DateTime? dateTo = null;
                        dateFrom = dtpDateFrom.Value; 
                        dateTo = dtpDateTo.Value;  
                        _rpt.ViewEmployeeSalesByCountryReport(dateFrom, dateTo);
                    }
                    break;
                case ReportType.Invoice:
                    int? orderId = null;
                    test = Int32.TryParse(this.OrderIDTextBox.Text, out id);
                    if (test) orderId = id;
                    _rpt.ViewInvoiceReport(orderId); 
                    break;
                case ReportType.ProductByCategory:
                    _rpt.ViewProductByCategoryReport();
                    break;
                case ReportType.SalesAnalysis:
                    _rpt.ViewSalesAnalysisReport();
                    break;
                case ReportType.SalesByCategory:
                    int? categoryId = null;
                    if (!string.IsNullOrEmpty(categoryIdComboBox.Text))
                    {
                        Northwind.NET.BLL.Reports.ProductCategoriesRow r = categoryIdComboBox.SelectedItem  as Northwind.NET.BLL.Reports.ProductCategoriesRow;
                        if (r != null) categoryId = r.CategoryID; 
                    }
                    _rpt.ViewSalesByCategoryReport(categoryId);
                    break;
                case ReportType.SalesByYear:
                    {
                        int? yearNum = null;
                        if (!string.IsNullOrEmpty(txtYear.Text))
                        {
                            test = Int32.TryParse(txtYear.Text, out id);
                            if (test) yearNum = id;
                        }
                        _rpt.ViewSalesByYearReport(yearNum);
                    }
                    break;
                case ReportType.SalesTotalsByAmount:
                    {
                        int? yearNum = null;
                        if (!string.IsNullOrEmpty(txtYear.Text))
                        {
                            test = Int32.TryParse(txtYear.Text, out id);
                            if (test) yearNum = id;
                        }
                        _rpt.ViewSalesTotalsByAmountReport(yearNum);
                    }
                    break;
                case ReportType.Shippers:
                    _rpt.ViewShippersReport();  
                    break;
                case ReportType.SummaryOfSalesByQuarter:
                    _rpt.ViewSummaryOfSalesByQuarterReport();
                    break;
                case ReportType.SummaryOfSalesByYear:
                    _rpt.ViewSummaryOfSalesByYearReport();
                    break;
            }

            if (ControlLoaded != null)
            {
                ControlLoaded
                (
                    this, new ControlLoadedEventArgs() 
                    { 
                        ControlName = reportType.ToString(),
                        ControlTitle = getReportTitleFromItsType(reportType)
                    }
                );
            }

        }

        private string getReportTitleFromItsType(ReportType reportType)
        {
            string type = reportType.ToString();
            string ret = "";
            foreach (char c in type)
            {
                if (string.IsNullOrEmpty(ret)) ret = c.ToString();
                else if (char.IsUpper(c)) ret += " " + c;
                else ret += c;
            }
            ret = ret.Replace("Report", "") + " Report"; 
            return ret;
        }

        private bool _lookupDataLoaded { get; set; }
        private void loadLookUpData(object sender, EventArgs e)
        {
            if (_lookupDataLoaded) return;
            
            countryComboBox.Items.Clear();
            countryComboBox.Items.Insert(0, "");
            foreach (string countryName in Northwind.NET.BLL.Reports.CustomerCountries()) countryComboBox.Items.Add(countryName);

            categoryIdComboBox.Items.Clear();
            categoryIdComboBox.DisplayMember = "CategoryName";
            categoryIdComboBox.ValueMember = "CategoryID";

            Northwind.NET.BLL.Reports.ProductCategoriesRow r = new Northwind.NET.BLL.Reports.ProductCategoriesRow() { CategoryID = null, CategoryName = "" };
            categoryIdComboBox.Items.Add(r);
            foreach (var v in Northwind.NET.BLL.Reports.ProductCategories())
            {
                categoryIdComboBox.Items.Add(v);
            }

            _lookupDataLoaded = true;  
        }

       //private bool _loadInProgress;
        private MyReportsViewer _rpt;
        private void ReportViewingUserControl_Load(object sender, EventArgs e)
        {
            try
            {
                //_loadInProgress = true;
                _rpt = new MyReportsViewer(this.reportViewer1);
                _rpt.LoadLookUpData += new EventHandler<EventArgs>(loadLookUpData);
            }
            finally
            {
                //_loadInProgress = false;
            }
        }

        private void catalogReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.Catalog);  
        }

        private void productByCategoryButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.ProductByCategory);
        }

        private void alphabeticalLiustOfProductsButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.AlphabeticalListOfProducts);
        }

        private void customersLabelsReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.CustomersLabelsReport);
        }

        private void cmdShippersReport_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.Shippers);
        }

        private void invoiceReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.Invoice);
        }

        private void summaryOfSalesByYearReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.SummaryOfSalesByYear);
        }

        private void summaryOfSalesByQuarterReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.SummaryOfSalesByQuarter);
        }

        private void salesByCategoryReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.SalesByCategory);
        }

        private void salesTotalsByAmountButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.SalesTotalsByAmount);
        }

        private void salesByYearReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.SalesByYear);
        }

        private void SalesAnalysisReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.SalesAnalysis);  
        }

        private void employeSalesByCountryReportButton_Click(object sender, EventArgs e)
        {
            viewReport(ReportType.EmployeeSalesByCountry);
        }

        private void countryComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_rpt != null && _rpt.CurrentReportType == ReportType.CustomersLabelsReport)
            {
                customersLabelsReportButton_Click(sender, e);
            }
        }

        private void categoryIdComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_rpt != null && _rpt.CurrentReportType == ReportType.SalesByCategory)
            {
                salesByCategoryReportButton_Click(sender, e);
            }
        }



    }
}
